import wsgiref.handlers, os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from django.utils import simplejson
from thomas import Bayes
#from utils import PTTokenizer
#from persistence import SQLitePersistence
from persistence import AppEngineStore


guesser = Bayes(None, None, None, AppEngineStore())
guesser.load(None)

class MainPage(webapp.RequestHandler):
	def get(self):
		_tpl = {}
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, _tpl))


class CheckMessageHandler(webapp.RequestHandler):

	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, _tpl))

	def post(self):
		body = self.request.get("body")#.decode("UTF-8")
		if body:
			res = guesser.guess(body)
			if len(res) == 0:
				self.response.out.write(simplejson.dumps("No classification for text %s" % (body)))
			else:
				self.response.out.write(simplejson.dumps(res))
		else:
			self.response.out.write(simplejson.dumps("Body is empty"))

class TrainHandler(webapp.RequestHandler):

	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, _tpl))

	def post(self):
		body = self.request.get("body")#.decode("UTF-8")
		tag = self.request.get("tag").decode("UTF-8")
		if body and tag:
			if tag.lower() not in ["positive", "negative"]:
				request.setResponseCode(http.INTERNAL_SERVER_ERROR)
				return simplejson.dumps("Error training")
			else:
				guesser.train(tag, body)
				res = "Trained %s for %s" % (body, tag)
				return simplejson.dumps(res)
		else:
			self.response.out.write(simplejson.dumps("Body or tag is empty"))

class Stats(webapp.RequestHandler):

	def get(self):
		self.response.out.write(guesser.poolNames())

def main():
	
	#guesser = Bayes(None, None, None, Pickler())
	#r = guesser.load("sentiment_data.sqlite")
	#if r == None:
	#	print "Error loading database"
	#	sys.exit(0)

	app = webapp.WSGIApplication([('/', MainPage), ('/train', TrainHandler), ('/check', CheckMessageHandler), ('/stats',Stats)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
	main()
